package com.vhall.component.plugin.common.utils;

import cn.hutool.core.date.DatePattern;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;

/**
 * @author rui.zhou
 * @date 2021/4/22 17:04
 */
public class DateUtils {

    /**
     * 将时间转换为时间戳
     */
    public static Long dateToStamp(String time, String format) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = simpleDateFormat.parse(time);
        } catch (ParseException e) {
            throw new ParseException("时间格式错误", 0);
        }
        //获取时间的时间戳
        long ts = date.getTime() / 1000;
        return ts;
    }

    public static String toSeconds(int seconds) {
        int temp = 0;
        StringBuffer sb = new StringBuffer();
        temp = seconds / 3600;
        sb.append((temp < 10) ? "0" + temp + ":" : "" + temp + ":");
        temp = seconds % 3600 / 60;
        sb.append((temp < 10) ? "0" + temp + ":" : "" + temp + ":");
        temp = seconds % 3600 % 60;
        sb.append((temp < 10) ? "0" + temp : "" + temp);
        return sb.toString();
    }

    public static String secToTime(int time) {
        String timeStr = null;
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time <= 0) {
            return "00:00";
        } else {
            minute = time / 60;
            if (minute < 60) {
                second = time % 60;
                timeStr = unitFormat(minute) + ":" + unitFormat(second);
            } else {
                hour = minute / 60;
                if (hour > 99) {
                    return "99:59:59";
                }
                minute = minute % 60;
                second = time - hour * 3600 - minute * 60;
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
            }
        }
        return timeStr;
    }

    public static String unitFormat(int i) {
        String retStr = null;
        if (i >= 0 && i < 10) {
            retStr = "0" + Integer.toString(i);
        } else {
            retStr = "" + i;
        }
        return retStr;
    }

    /**
     * 计算时间差 并转成yyyy-MM-dd HH:mm:ss时间格式的字符串
     *
     * @param sec1
     * @param sec2
     * @return
     */
    public static String timestampFormat(Integer sec1, Integer sec2) {
        int timestamp = sec1 - sec2;
        LocalDateTime time = LocalDateTime.ofEpochSecond(timestamp, 0, ZoneOffset.ofHours(8));
        return time.format(DatePattern.NORM_DATETIME_FORMATTER);
    }

}
